import React, { Component } from 'react'
import { inject } from 'mobx-react/index'
import {
  Form,
  Input,
  Radio,
  Button,
  message,
  Spin,
} from 'antd'
import _ from 'lodash'
import getData from '@/Utils/fecth'
import Title from '@/components/Title'
import { address } from '@/Utils/apiConfig'

import './index.less'

const { quorumManagement: { createQuorumList }} = address
const { TextArea } = Input

// @inject("SocketModel")
@inject('QuorumNetwork')
class CreateNetwork extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mode: 'out',
      type: 'orderer',
      caList: [],
      peerList: [],
      expiration: 1,
      // 初始值
      initialValues: {
        name: '',
        network_id: '',
        consensus: 'istanbul',
        gaslimit: '',
        network_des: '',
        // node_num: "",
        performance: 'ecs.c5.large',
        expiration: 1,
        org_description: '',
      },
      // 右边当前选中值
      currentValues: {
        name: '',
        network_id: '',
        consensus: 'Istanbul',
        gaslimit: '',
        network_des: '',
        // node_num: "",
        performance: '标准版',
        expiration: 1,
        total_price: '',
      },
      loading: false,
      checkPeerFlag: 'false',
      peerDatas: [
        {
          key: 'check_node',
          type: '验证节点',
          size: '2c4g 300GB',
          num: 3,
        },
        {
          key: 'normal_node',
          type: '普通节点',
          size: '2c4g 300GB',
          num: 2,
        },
      ],
    }
    this.quorum = []
    this.caList = []
    this.peerList = []
    this.createKey = 2
  }
  formNetwork = React.createRef();

  // 表单真实的数据提交
  // 构建组织-云节点模式提交
  onFinish = async(values) => {
    this.setState({
      loading: true,
    })
    let obj = {
      ...values,
      expiration: values.expiration.toString(),
      resources_pool: '1',
    }

    const res = await getData().post(createQuorumList, obj)
    if (res) {
      if (res.status === 200) {
        message.success('网络新建中...')
        this.props.history.goBack()
      }
    }

    // const _this = this;
    // this.timer = setTimeout(() => {
    //   _this.props.QuorumNetwork.setNetworkStatus(this.createkey, 'success')
    // }, 3000)
    this.setState({
      loading: false,
    })
    //
  };

  onChange = (values) => {
    let currentValues = {
      ...this.state.currentValues,
      ...values,
    }
    this.setState({
      currentValues,
    })
  };
  submit = () => {
    this.formNetwork.current.submit()
  };

  // 构建组织-外部节点模式提交
  createOrg = async(values) => {
    const { checkPeerFlag } = this.state
    if (checkPeerFlag !== 'true') { message.warn('请填写正确的节点信息'); return false }
    let res = {}
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      message.success('创建组织成功!')
      this.props.history.goBack()
    } else {
      message.error('创建组织失败')
    }
  };

  componentWillUnmount() {
    this.timer = null
    this.timer && clearTimeout(this.timer)
  }

  render() {
    const { initialValues, currentValues, loading } = this.state
    const org_expiration = {
      1: '一个月',
      6: '半年',
      12: '一年',
    }
    return (
      <div className="fabric-create-org">
        <Spin spinning={loading}>

          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
            <div className="tabs-wrapper">
              <Title title="填写配置" />
              <Form
                className="create-form bare-form "
                ref={this.formNetwork}
                onValuesChange={(changedValues, allValues) =>
                  this.onChange(changedValues)
                }
                initialValues={initialValues}
                onFinish={this.onFinish}
              >
                <Form.Item
                  name="name"
                  label="网络名称"
                  className="form-item"
                  help="请输入网络名称，最多输入30字符"
                  rules={[
                    { required: true, message: '请输入网络名称！' },
                    ({ getFieldValue }) => ({
                      validator(rule, value) {
                        let r = /^[^\u4e00-\u9fa5]+$/
                        if (value) {
                          if (!r.test(value)) {
                            return Promise.reject('网络名称不能包含中文！')
                          } else if (/[_]/g.test(value)) {
                            return Promise.reject('网络名称不能包含下划线！')
                          } else if (/[A-Z]/g.test(value)) {
                            return Promise.reject('网络名称不能包含大写字母！')
                          } else {
                            return Promise.resolve()
                          }
                        } else {
                          return Promise.resolve()
                        }
                      },
                    }),
                  ]}
                >
                  <Input
                    placeholder="请输入网络名称，最多输入30字符"
                    className="input"
                    maxLength={30}
                    autoComplete="off"
                  />
                </Form.Item>
                {/* <Form.Item
                    name="network_id"
                    label="网络ID"
                    className="form-item"
                    rules={[
                      { required: true, message: "请输入网络ID！" },
                      ({ getFieldValue }) => ({
                        validator(rule, value) {
                          let r = /^[^\u4e00-\u9fa5]+$/;
                          if (value) {
                            if (!r.test(value)) {
                              return Promise.reject("网络ID不能包含中文！");
                            }else  {
                              return Promise.resolve();
                            }
                          } else {
                            return Promise.resolve();
                          }
                        },
                      }),
                    ]}
                  >
                    <Input
                      placeholder="请填写网络ID,最多输入20字符"
                      maxLength={20}
                      className="input"
                      autoComplete="off"
                    />
                  </Form.Item> */}
                <Form.Item
                  name="consensus"
                  label="共识算法"
                  className="form-item"
                  rules={[{ required: true, message: '请选择共识算法！' }]}
                >
                  <Radio.Group>
                    <Radio.Button value="istanbul">Istanbul</Radio.Button>
                    <Radio.Button value="raft">Raft</Radio.Button>
                  </Radio.Group>
                </Form.Item>
                {/* <Form.Item
                    name="gaslimit"
                    label="Gaslimit"
                    className="form-item"
                    rules={[
                      { required: true, message: "请输入Gaslimit！" }
                    ]}
                  >
                    <Input
                      placeholder="请输入Gaslimit，最多输入20字符"
                      className="input"
                      maxLength={20}
                      autoComplete="off"
                    />
                  </Form.Item> */}
                <Form.Item
                  name="detail"
                  label="描述"
                  maxLength={250}
                  className="form-item"
                >
                  <TextArea rows={4} maxLength={500}/>
                </Form.Item>
                <div className="diver"></div>
                {/* <Form.Item
                    label="节点"
                    style={{ textTransform: "capitalize" }}
                    rules={[
                      { required: true, message: "请输入节点信息！" }
                    ]}
                    className="form-item form-item-peer"
                  >

                      {
                        peerDatas.map(item => {
                          return (<div className="item-peer" key={item.key}>
                            <span className="peer-type">{item.type}</span><span className="diver"></span>
                            <span className="peer-size">{item.size}</span><span className="diver"></span>
                            <span className="peer-num">数量：</span>{item.num}
                          </div>)
                        })
                      }

                  </Form.Item> */}
                {/* <div className="diver"></div> */}
                <Form.Item
                  name="expiration"
                  label="购买时长"
                  className="form-item three-radio"
                >
                  <div className="radio-group">
                    <div className={this.state.expiration === 1 ? 'view view-select' : 'view'} onClick={() => { this.setState({ expiration: 1 }), this.formNetwork.current.setFieldsValue({ expiration: 1 }), this.onChange({ expiration: 1 }) }}>一个月</div>
                    <div className={this.state.expiration === 6 ? 'view view-select' : 'view'} onClick={() => { this.setState({ expiration: 6 }), this.formNetwork.current.setFieldsValue({ expiration: 6 }), this.onChange({ expiration: 6 }) }}>半年</div>
                    <div className={this.state.expiration === 12 ? 'view view-select' : 'view'}onClick={() => { this.setState({ expiration: 12 }), this.formNetwork.current.setFieldsValue({ expiration: 12 }), this.onChange({ expiration: 12 }) }}>一年</div>
                  </div>
                </Form.Item>
              </Form>
            </div>

            <div className="org-current-info current-info">
              <Title title="当前配置" />
              <div className="info">
                <div className="item-info">
                  <span className="item-text">网络名称</span>
                  <span className="item-value">
                    {currentValues.name || '-'}
                  </span>
                </div>
                {/* <div className="item-info">
                    <span className="item-text">网络ID</span>
                    <span className="item-value">
                      {currentValues.network_id || "-"}
                    </span>
                  </div> */}
                <div className="item-info">
                  <span className="item-text">共识算法</span>
                  <span
                    className="item-value"
                    style={{ textTransform: 'capitalize' }}
                  >
                    {currentValues.consensus}
                  </span>
                </div>
                {/* <div className="item-info">
                    <span className="item-text">Gaslimit</span>
                    <span className="item-value">
                      {currentValues.gaslimit}
                    </span>
                  </div> */}
                <div className="diver"></div>
                {/* <div className="item-info item-info-peer">
                    <span className="item-text">节点</span>
                    <span className="item-value item-peer-wrap">
                      {
                        peerDatas.map(item => {
                          return (<div className="item-peer" key={item.key}>
                            <span className="peer-type">{item.type}</span><span className="diver"></span>
                            <span className="peer-size">{item.size}</span><span className="diver"></span>
                            <span className="peer-num">数量：</span>{item.num}
                          </div>)
                        })
                      }
                    </span>
                  </div>
                  <div className="diver"></div> */}
                <div className="item-info">
                  <span className="item-text">购买时长</span>
                  <span className="item-value">
                    {_.get(org_expiration, currentValues.expiration)}
                  </span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">配置费用</span>
                  <span className="item-value">
                    <span className="symbol">¥</span>11988.00
                  </span>
                </div>
              </div>
              <div className="btn">
                <Button
                  className="buy-btn"
                  onClick={() => this.submit()}
                  type="submit"
                >
                    立即购买
                </Button>
              </div>
            </div>
          </div>

        </Spin>
      </div>
    )
  }
}
export default CreateNetwork
